var express = require('express');
var router = express.Router();
const { listModel } = require('../db/index');

// GET /list?page=1&pageSize=10
router.get('/list', async (req, res) => {
  const { page = 1, pageSize = 10, category, keyword } = req.query;

  let query = {};
  if (category && category !== '全部') query.type = category;
  if (keyword) query.title = new RegExp(keyword, 'i');

  const skip = (page - 1) * pageSize;
  const limit = Number(pageSize);

  const [data, total] = await Promise.all([
    listModel.find(query).skip(skip).limit(limit),
    listModel.countDocuments(query)
  ]);

  const hasMore = skip + data.length < total;

  res.send({
    info: data,
    total,
    hasMore
  });
});

router.get('/item', async (req, res) => {
  const { id } = req.query;
  const data = await listModel.findById(id);
  res.send({ info: data }); 
})
//猜你喜欢接口
router.get("/recommend", async (req, res) => {
  const { category, exclude } = req.query;

  try {
    const query = {
      type:category,
      _id: { $ne: exclude }, // 排除当前商品
    };

    const list = await listModel.aggregate([
      { $match: query },
      { $sample: { size: 6 } }, // 随机推荐 6 个
    ]);

    res.send({ code: 0, info: list });
  } catch (err) {
    console.error("获取猜你喜欢失败", err);
    res.status(500).json({ code: 1, msg: "获取猜你喜欢失败" });
  }
});


router.get('/search', async (req, res) => {
  const { keyword } = req.query;
  const result = await listModel.find({
    title: { $regex: keyword, $options: 'i' } // 模糊匹配，不区分大小写
  });
  res.send({ info: result });
});

//收藏接口
router.post('/collect', async (req, res) => {
  const { id, isCollect } = req.body;

  if (!id || typeof isCollect !== 'boolean') {
    return res.send({ code: 1, msg: '参数错误' });
  }

  try {
    const result = await listModel.findByIdAndUpdate(
      id,
      { collect: isCollect },  // 注意字段名应与你数据库中的一致
      { new: true }
    );

    if (!result) {
      return res.send({ code: 1, msg: '未找到该商品' });
    }

    res.send({ code: 0, msg: isCollect ? '收藏成功' : '取消收藏成功', info: result });
  } catch (err) {
    console.error(err);
    res.send({ code: 1, msg: '收藏失败', error: err });
  }
});

// 获取收藏状态接口
router.get("/collect-status", async (req, res) => {
  const { id } = req.query;

  if (!id) {
    return res.send({ code: 1, msg: "缺少参数 id" });
  }

  try {
    const item = await listModel.findById(id).select("collect");

    if (!item) {
      return res.send({ code: 1, msg: "商品不存在" });
    }

    res.send({ code: 0, collect: item.collect });
  } catch (err) {
    console.error(err);
    res.send({ code: 1, msg: "查询失败", error: err });
  }
});

module.exports = router;
